using LPP.API.Controllers;
using LPP.Core.Alipay;
using LPP.Core.Aliyun;
using LPP.Core.Dtos;
using LPP.Core.Jwt;
using LPP.Core.Services;
using LPP.Core.WeChat;
using LPP.Entity.Orders;
using LPP.EntityFrameworkCore;
using LPP.Repository;
using LPP.Repository.AddressRepository;
using LPP.Repository.BookingRepository;
using LPP.Repository.BusRepository;
using LPP.Repository.Medias;
using LPP.Repository.NotificationRepository;
using LPP.Repository.PaymentRecordRepository;
using LPP.Repository.Repositories;
using LPP.Repository.UserReviewRepository;
using LPP.Repository.WorkerRepository;
using LPP.Service;
using LPP.Service.AddressService;
using LPP.Service.BookingService;
using LPP.Service.BusServices;
using LPP.Service.ChatService;
using LPP.Service.MapServices;
using LPP.Service.MediaService;
using LPP.Service.NotificationService;
using LPP.Service.OrderServices;
using LPP.Service.payment;
using LPP.Service.Payment;
using LPP.Service.TokenService;
using LPP.Service.UserRepository;
using LPP.Service.UserReviewService;
using LPP.Service.WorkerService;
using LPP.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Text;
using Microsoft.Extensions.Caching.Memory;
using LPP.Service.SmsService;

var builder = WebApplication.CreateBuilder(args);
ConfigurationManager configuration = builder.Configuration;

// 添加 CORS 配置
builder.Services.AddCors(options =>
{
    options.AddPolicy("Cors", config =>
    {
        config.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();
    });
});

// 配置数据库
builder.Services.AddDbContext<SqlDbContext>(options =>
{
    options.UseSqlServer(configuration.GetConnectionString("strConn"), sqlOptions =>
    {
        sqlOptions.EnableRetryOnFailure(5, TimeSpan.FromSeconds(30), null);
        sqlOptions.CommandTimeout(30);
    });
});

// 配置 JWT
var jwtSection = configuration.GetSection("TokenManagement");
builder.Services.Configure<TokenManagement>(jwtSection);
var tokenManagement = jwtSection.Get<TokenManagement>();
builder.Services.AddSingleton(tokenManagement);

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.RequireHttpsMetadata = false;
        options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenManagement.Secret)),
            ValidateIssuer = false,  // 关闭 Issuer 验证
            ValidateAudience = false, // 关闭 Audience 验证
            ValidateLifetime = true,
            ClockSkew = TimeSpan.FromSeconds(30),
            RequireExpirationTime = true,
        };
    });

// 注册依赖项
builder.Services.AddMemoryCache();
builder.Services.AddScoped<IPaymentService, PaymentService>();
builder.Services.AddScoped<IAlipayService, AlipayService>();
builder.Services.AddScoped<IWeChatPayService, WeChatPayService>();
builder.Services.AddScoped<IMediaRepository, MediaRepository>();
builder.Services.AddScoped<IMediaService, MediaService>();
builder.Services.AddScoped<IBookingService, BookingService>();
builder.Services.AddScoped<IBookingRepository, BookingRepository>();
builder.Services.AddScoped<INotificationRepository, NotificationRepository>();
builder.Services.AddScoped<INotificationService, NotificationService>();
builder.Services.AddScoped<IStatisticService, StatisticService>();
builder.Services.AddScoped<ILogService, LogService>();
builder.Services.AddScoped<SmsService, SmsService>();  // 注册短信服务
builder.Services.AddScoped<LPP.Repository.SmsVerificationRepository>();
builder.Services.AddScoped<IOrderRepository, OrderRepository>();
builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<UserReviewService>();
builder.Services.AddScoped<UserReviewRepository>();
builder.Services.AddScoped<IWorkerService, WorkService>();
builder.Services.AddScoped<IWorkerRepository, WorkerRepository>();
builder.Services.AddScoped<IImageUploadService, ImageUploadService>();
builder.Services.AddScoped<ITokenService, TokenService>();
builder.Services.Configure<AlipayConfig>(configuration.GetSection("Alipay"));
builder.Services.AddScoped<IPaymentRecordRepository, PaymentRecordRepository>();

// 配置 Swagger
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        In = ParameterLocation.Header,
        Description = "请输入 'Bearer' + 空格 + Token",
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey,
        BearerFormat = "JWT",
        Scheme = "Bearer"
    });
    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
            },
            new string[] { }
        }
    });
});
builder.Services.AddAuthorization();
builder.Services.AddControllers();

var app = builder.Build();

// 启用 Swagger
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"));
}

app.UseHttpsRedirection();
app.UseCors("Cors");
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
